<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <button @click="str = 'Child1'">child1</button>
      <button @click="str = 'Child2'">child2</button>
      <button @click="str = 'Child3'">child3</button>

      <!-- keep-alive，vue提供的一个用于缓存组件的标签 -->
      <keep-alive>
        <component :is="str"></component>
      </keep-alive>
    </div>

    <script src="../Vue.js"></script>
    <script>
      const Child1 = {
        template: `
          <div>child1组件</div>
        `,
      };
      let timer;
      const Child2 = {
        data() {
          return {
            count: 1,
          };
        },
        template: `
          <div>child2组件 - {{ count }}</div>
        `,
        mounted() {
          console.log("child2 mounted");

          // timer = setInterval(() => {
          //   this.count++;
          //   console.log(111);
          // }, 1000);
        },
        beforeDestroy() {
          clearInterval(timer);
          console.log("child2 destroy");
        },
        activated() {
          // 表示被 keep-alive 缓存的组件激活时调用。
          console.log("child2 被激活了");
          timer = setInterval(() => {
            this.count++;
            console.log(111);
          }, 1000);
        },
        deactivated() {
          // 表示被 keep-alive 缓存的组件失活时调用。
          console.log("child2 被失活了");
          clearInterval(timer);
        },
      };
      const Child3 = {
        template: `
          <div>child3组件</div>
        `,
      };
      new Vue({
        el: "#app",
        data: {
          num: 1,
          str: "Child1",
        },
        components: {
          Child1,
          Child2,
          Child3,
        },
      });
    </script>
  </body>
</html>
